package com.you.mavenbuildtest.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ProxyController {
    public static Map<String,Object> map = new HashMap<>();
    @PostConstruct
    public void init(){
        map.put("ProxyController",this);
    }

    @RequestMapping(value = "/proxy", method = RequestMethod.GET)
    public String proxy(){
        String proxyHost="182.61.200.7";
        String proxyPort="80";//代理端口

        InputStreamReader isr = null;

        String json = null;
        try {
            URL mapAPI = new URL("https://www.baidu.com/");
            //2、创建url代理服务
            InetSocketAddress address=new InetSocketAddress(proxyHost,Integer.parseInt(proxyPort));
            Proxy proxy=new Proxy(Proxy.Type.HTTP,address);
            URLConnection connection = mapAPI.openConnection(proxy);
            isr = new InputStreamReader(connection.getInputStream(), "utf-8");
            json= IOUtils.toString(isr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(isr != null)
                    isr.close();
            } catch (IOException e) {
            }
        }
        return json;
    }

    @RequestMapping(value = "/getReq")
    public void getReq(String id){
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        System.out.println(String.format("获取到的对象, %s",attributes));
    }
}
